package com.youfang.sixthmedia.ui.weibo;

import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;

import com.gzit.utils.AndroidUtils;
import com.gzit.utils.StringUtils;
import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;
import com.youfang.sixthmedia.common.YoufangContext;

public class TencentWeiboActivity extends WeiboActivity {

	/*
	 * 申请APP KEY的具体介绍，可参见 http://wiki.open.t.qq.com/index.php/应用接入指引 
	 * http://wiki.
	 * open.t.qq.com/index.php/腾讯微博移动应用接入规范#.E6.8E.A5.E5.85.A5.E6.B5.81.E7.A8.8B 
	 */
	// !!!请根据您的实际情况修改!!! 认证成功后浏览器会被重定向到这个url中 必须与注册时填写的一致
	// private String redirectUri = "http://www.tencent.com/zh-cn/index.shtml";
	private String redirectUri = "http://www.sixthmedia.net/";
	// !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP KEY
	private String clientId = "801094913";
	// !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP SECRET
	private String clientSecret = "4ece63eccde4496286f4a2dc371d1e7f"; 

	protected OAuthV2 oAuth;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
	}

	protected void init() {

		oAuth = new OAuthV2(redirectUri);
		oAuth.setClientId(clientId);
		oAuth.setClientSecret(clientSecret);

		// 关闭OAuthV2Client中的默认开启的QHttpClient。
		OAuthV2Client.getQHttpClient().shutdownConnection();
	}

	protected void gotoOAuthActivity() {

		// 创建Intent，使用WebView让用户授权
		Intent intent = new Intent(this, OAuthV2AuthorizeWebView.class);
		intent.putExtra("oauth", oAuth);
		startActivityForResult(intent, OAUTH_REQUEST);

	}

	protected boolean sendWeibo(String content, String picPath) {

		new WeiboTask(this) {

			@Override
			boolean doTask(String... params) {

				TAPI tAPI = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
				try {

					String response = null;

					// if now pic presented ,used add api
					if (StringUtils.isBlank(params[1])) {
						response = tAPI.add(oAuth, "json", params[0],
								"127.0.0.1");
					} else {
						response = tAPI.addPic(oAuth, "json", params[0],
								"127.0.0.1", params[1]);
					}

					JSONObject json = new JSONObject(response);
					if (json.getInt("errcode") != 0) {
						return false;
					}

				} catch (Exception e) {
					e.printStackTrace();
					return false;
				} finally {
					tAPI.shutdownConnection();
				}

				return true;
			}

			@Override
			void callback(boolean result) {
				AndroidUtils.toastShort(result ? "微博发送成功" : "微博发送失败");
			}

		}.execute(content, picPath);

		return true;
	}

	private static final int OAUTH_REQUEST = 2;

	/*
	 * 通过读取OAuthV2AuthorizeWebView返回的Intent，获取用户授权信息
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == OAUTH_REQUEST) {
			if (resultCode == OAuthV2AuthorizeWebView.RESULT_CODE) {
				oAuth = (OAuthV2) data.getExtras().getSerializable("oauth");
				onOAuthCallback(oAuth.getStatus() == 0);
			}
		}
	}

	protected void clearStoreSP() {

		Editor editor = YoufangContext.prepare();
		editor.remove("qq_token");
		editor.remove("qq_expired");
		editor.remove("qq_openid");
		editor.remove("qq_openkey");
		editor.clear();

	}

	protected boolean isAlreadyAuthed() {

		SharedPreferences sp = YoufangContext.getSharedPreferences();
		String token = sp.getString("qq_token", null);
		long expired = sp.getLong("qq_expired", -1);

		if (StringUtils.isBlank(token)) {
			return false;
		}

		// expired?
		if (System.currentTimeMillis() > expired) {
			return false;
		}

		String openid = sp.getString("qq_openid", null);
		String openkey = sp.getString("qq_openkey", null);

		oAuth.setAccessToken(token);
		oAuth.setOpenid(openid);
		oAuth.setOpenkey(openkey);

		return true;

	}

	protected String getNickName() {
		SharedPreferences sp = YoufangContext.getSharedPreferences();
		return sp.getString("qq_nick", "");

	}

	protected boolean fecthUserInfoAndStoreIt() {

		// fetched user info...
		new WeiboTask(this) {

			@Override
			boolean doTask(String... params) {

				UserAPI userAPI = new UserAPI(OAuthConstants.OAUTH_VERSION_2_A);

				String nick = "";
				try {
					String userInfo = userAPI.info(oAuth, "json");

					// extract nick name from result
					JSONObject json = new JSONObject(userInfo);
					JSONObject data = json.getJSONObject("data");
					if (json.getInt("errcode") != 0) {
						AndroidUtils.toastShort("获取微博的个人信息失败");
						return false;
					}
					if (data.has("nick")) {
						nick = data.getString("nick");
					}
					Log.i("qq weibo", userInfo);

					// save nick name
					Editor editor = YoufangContext.prepare();
					editor.putString("qq_nick", nick);
					editor.commit();

				} catch (Exception e) {
					e.printStackTrace();
					return false;
				} finally {
					userAPI.shutdownConnection();

				}

				return true;

			}

			@Override
			void callback(boolean result) {
				if (!result) {
					AndroidUtils.toastShort("授权失败，无法取得微博的个人信息");
					return;
				}

				// save oauth result
				String expired = oAuth.getExpiresIn();
				String accessToken = oAuth.getAccessToken();
				String openID = oAuth.getOpenid();
				String openKey = oAuth.getOpenkey();

				Editor editor = YoufangContext.prepare();
				editor.putString("qq_token", accessToken);

				// oauth expired in XX second,we use this infomation to
				// calculate
				// the expired date
				editor.putLong("qq_expired", Long.parseLong(expired) * 1000
						+ System.currentTimeMillis() - 60 * 60 * 1000);

				editor.putString("qq_openid", openID);
				editor.putString("qq_openkey", openKey);

				editor.commit();

			}
		}.execute("");

		return true;

	}

	@Override
	protected void onOAuthCallback(boolean ok) {
		if (ok) {
			fecthUserInfoAndStoreIt();
		}

	}
}
